package com.hylanda.tools;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.Map;
import java.util.Map.Entry;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;

public class HttpTools {

	public static String DownHttps(String tokenUrl) {
		StringBuffer buffer = new StringBuffer();
		try {
			// 建立连接
			URL url = new URL(tokenUrl);

			HttpsURLConnection httpUrlConn = (HttpsURLConnection) url
					.openConnection();

			// 创建SSLContext对象，并使用我们指定的信任管理器初始�?
			TrustManager[] tm = { new MyX509TrustManager() };
			SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
			sslContext.init(null, tm, new java.security.SecureRandom());
			// 从上述SSLContext对象中得到SSLSocketFactory对象
			SSLSocketFactory ssf = sslContext.getSocketFactory();

			httpUrlConn.setSSLSocketFactory(ssf);
			httpUrlConn.setDoOutput(true);
			httpUrlConn.setDoInput(true);

			// 设置请求方式（GET/POST�?
			httpUrlConn.setRequestMethod("GET");

			// 取得输入�?
			InputStream inputStream = httpUrlConn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(
					inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
			// 读取响应内容
			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			// 释放资源
			inputStream.close();
			httpUrlConn.disconnect();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchProviderException e) {
			e.printStackTrace();
		} catch (KeyManagementException e) {
			e.printStackTrace();
		}
		return buffer.toString();
	}
	

    //post请求
    public static String PostHttps(String requestUrl, Map<String,String> headers,String data) {
        StringBuffer buffer = new StringBuffer();
 
        BufferedReader bufferedReader = null;
        OutputStream outputStream = null;
        HttpsURLConnection httpUrlConn = null;
 
        try {
            // 创建SSLContext对象，并使用我们指定的信任管理器初始�?
            TrustManager[] tm = { new MyX509TrustManager() };
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();
 
            httpUrlConn = (HttpsURLConnection) createHttpURLConnection(requestUrl);
            httpUrlConn.setSSLSocketFactory(ssf);
            httpUrlConn.setRequestMethod("POST");
            addHeaders(httpUrlConn,headers);
            // 当有数据�?要提交时
            if (null != data) {
                outputStream = httpUrlConn.getOutputStream();
                // 注意编码格式，防止中文乱�?
                outputStream.write(data.getBytes("UTF-8"));
                outputStream.flush();
            }
 
            // 将返回的输入流转换成字符�?
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
            bufferedReader = new BufferedReader(inputStreamReader);
 
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            return buffer.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            close(bufferedReader,outputStream,httpUrlConn);
        }
        return null;
    }
    

    //PUT请求
    public static String PutHttp(String requestUrl, Map<String,String> headers,String data) {
        StringBuffer buffer = new StringBuffer();
 
        BufferedReader bufferedReader = null;
        OutputStream outputStream = null;
        HttpURLConnection httpUrlConn = null;
 
        try {
            httpUrlConn = (HttpURLConnection) createHttpURLConnection(requestUrl);
            httpUrlConn.setRequestMethod("PUT");
            addHeaders(httpUrlConn,headers);
            // 当有数据�?要提交时
            if (null != data) {
                outputStream = httpUrlConn.getOutputStream();
                // 注意编码格式，防止中文乱�?
                outputStream.write(data.getBytes("UTF-8"));
                outputStream.flush();
            }
 
            // 将返回的输入流转换成字符�?
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
            bufferedReader = new BufferedReader(inputStreamReader);
 
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            return buffer.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            close(bufferedReader,outputStream,httpUrlConn);
        }
        return null;
    }
    

    //PUT请求
    public static String DeleateHttp(String requestUrl, Map<String,String> headers,String data) {
        StringBuffer buffer = new StringBuffer();
 
        BufferedReader bufferedReader = null;
        OutputStream outputStream = null;
        HttpURLConnection httpUrlConn = null;
 
        try {
            httpUrlConn = (HttpURLConnection) createHttpURLConnection(requestUrl);
            httpUrlConn.setRequestMethod("DELETE");
            addHeaders(httpUrlConn,headers);
            // 当有数据�?要提交时
            if (null != data) {
                outputStream = httpUrlConn.getOutputStream();
                // 注意编码格式，防止中文乱�?
                outputStream.write(data.getBytes("UTF-8"));
                outputStream.flush();
            }
 
            // 将返回的输入流转换成字符�?
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
            bufferedReader = new BufferedReader(inputStreamReader);
 
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            return buffer.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            close(bufferedReader,outputStream,httpUrlConn);
        }
        return null;
    }
    
    

    //post请求
    public static String PostHttp(String requestUrl, Map<String,String> headers,String data) {
        StringBuffer buffer = new StringBuffer();
 
        BufferedReader bufferedReader = null;
        OutputStream outputStream = null;
        HttpURLConnection httpUrlConn = null;
 
        try {
            httpUrlConn = (HttpURLConnection) createHttpURLConnection(requestUrl);
            httpUrlConn.setRequestMethod("POST");
            addHeaders(httpUrlConn,headers);
            // 当有数据�?要提交时
            if (null != data) {
                outputStream = httpUrlConn.getOutputStream();
                // 注意编码格式，防止中文乱�?
                outputStream.write(data.getBytes("UTF-8"));
                outputStream.flush();
            }
 
            // 将返回的输入流转换成字符�?
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
            bufferedReader = new BufferedReader(inputStreamReader);
 
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
                buffer.append("\r\n");
            }
            return buffer.toString();
        } catch (Exception e) {
        	System.out.println(requestUrl);
            e.printStackTrace();
        }finally {
            close(bufferedReader,outputStream,httpUrlConn);
        }
        return null;
    }
	private static void close(BufferedReader bufferedReader,
			OutputStream outputStream, HttpURLConnection httpUrlConn) {
		if (outputStream != null) {
			try {
				outputStream.close();
			} catch (Throwable e) {
				System.err.println("关闭流失�?!"+e.getMessage());
			}
		}
		if (bufferedReader != null) {
			try {
				bufferedReader.close();
			} catch (Throwable e) {
				System.err.println("关闭流失�?!"+e.getMessage());
			}
		}
		if (httpUrlConn != null) {
			try {
				httpUrlConn.disconnect();
			} catch (Throwable e) {
				System.err.println("关闭连接失败!"+e.getMessage());
			}
		}
	}
    private static void addHeaders(HttpURLConnection httpURLConnection,Map<String,String> headers){
        if(headers==null){
            return;
        }
        for(Entry<String,String> header:headers.entrySet()){
            String key = header.getKey();
            String value = header.getValue();
            httpURLConnection.addRequestProperty(key, value);
        }
    }
    
    private static HttpURLConnection createHttpURLConnection(String requestUrl){
        URL url = null;
        HttpURLConnection httpUrlConn = null;
        try {
            url = new URL(requestUrl);
            httpUrlConn = (HttpURLConnection) url.openConnection();
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
        httpUrlConn.setDoOutput(true);
        httpUrlConn.setDoInput(true);
        httpUrlConn.setUseCaches(false);
        return httpUrlConn;
    }
     

    /**
     * URL编码（utf-8�?
     * 
     * @param source
     * @return
     */
    public static String urlEncodeUTF8(String source) {
        String result = source;
        try {
            result = java.net.URLEncoder.encode(source, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }
    
    /**
     * 根据内容类型判断文件扩展�?
     * 
     * @param contentType 内容类型
     * @return
     */
    public static String getFileExt(String contentType) {
        String fileExt = "";
        if ("image/jpeg".equals(contentType))
            fileExt = ".jpg";
        else if ("audio/mpeg".equals(contentType))
            fileExt = ".mp3";
        else if ("audio/amr".equals(contentType))
            fileExt = ".amr";
        else if ("video/mp4".equals(contentType))
            fileExt = ".mp4";
        else if ("video/mpeg4".equals(contentType))
            fileExt = ".mp4";
        return fileExt;
    }
    
    
    /***
	 * 下载二进制内容，如图片
	 * @param url
	 * @param refer
	 * @return
	 */
	public static byte[] doGetBinary(String url, String refer, String proxyIP, String proxyPort) {
		byte[] returnData = null;
		HttpClient httpclient = new DefaultHttpClient();
		try {
			httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
			httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 60000);
			HttpGet httpGet = new HttpGet(url);
			if (refer == null || refer.length() == 0) {
				refer = url;
			}

			// 设置代理服务器的ip地址和端口
			if (proxyIP != null && proxyPort != null) {
				HttpHost proxy = new HttpHost(proxyIP, Integer.valueOf(proxyPort).intValue());
				httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
			}

			// 設置httpGet的头部參數信息
			httpGet.setHeader("Accept", "Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
			// httpGet.setHeader("Accept-Charset",
			// "GB2312,utf-8;q=0.7,*;q=0.7");
			// httpGet.setHeader("Accept-Encoding", "gzip,deflate");
			// httpGet.setHeader("Accept-Language", "zh-cn,zh;q=0.5");
			httpGet.setHeader("Connection", "keep-alive");
			// httpGet.setHeader("Cookie",
			// "__utma=226521935.73826752.1323672782.1325068020.1328770420.6;");
			// httpGet.setHeader("Host", "www.cnblogs.com");
			httpGet.setHeader("refer", refer);
			httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; rv:6.0.2) Gecko/20100101 Firefox/6.0.2");

			HttpResponse response = httpclient.execute(httpGet);
			int nCode = response.getStatusLine().getStatusCode();
			if (nCode == 200) {
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					returnData = EntityUtils.toByteArray(entity);
				}
			} else {
				System.out.println(url + " resCode:" + nCode);
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

		finally {
			httpclient.getConnectionManager().shutdown();
		}
		return returnData;
	}
	
	@SuppressWarnings("deprecation")
	public static String doGet(String url,Map<String, String> headerMap) {
		String responseBody = "";
		boolean bOk = false;
		HttpClient httpclient = new DefaultHttpClient();
		try {
			httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
			httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 60000);
			HttpGet httpget = new HttpGet(url);
			if(headerMap != null && headerMap.size() > 0){
				for(String head:headerMap.keySet()){
					httpget.setHeader(head,headerMap.get(head));
				}
			}
			
			HttpResponse response = httpclient.execute(httpget);
			int nCode = response.getStatusLine().getStatusCode();
			if (nCode == 200) {
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					// responseBody = EntityUtils.toString(entity);
					responseBody = new String(EntityUtils.toByteArray(entity), "UTF-8");
					bOk = true;
				}
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

		finally {
			httpclient.getConnectionManager().shutdown();
		}

		return responseBody;

	}
    
	public static boolean doDownload(String url, String strFile) {
		boolean bOk = false;
		HttpClient httpclient = new DefaultHttpClient();
		try {
			httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
			httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 60000);

			HttpGet httpget = new HttpGet(url);
			HttpResponse response = httpclient.execute(httpget);
			int nCode = response.getStatusLine().getStatusCode();
			if (nCode == 200) {
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					byte[] bytes = EntityUtils.toByteArray(entity);
					File storeFile = new File(strFile);
					FileOutputStream output = new FileOutputStream(storeFile);

					output.write(bytes);
					output.close();
					bOk = true;
				}
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			httpclient.getConnectionManager().shutdown();
		}

		return bOk;
	}
     
	public static String doGetLastModify(String url) {
		boolean bOk = false;
		String strLastModify = "";
		HttpClient httpclient = new DefaultHttpClient();
		try {
			httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
			httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 60000);
			HttpGet httpget = new HttpGet(url);
			HttpResponse response = httpclient.execute(httpget);
			int nCode = response.getStatusLine().getStatusCode();

			if (nCode == 200) {
				Header[] aHeaders = response.getHeaders(HttpHeaders.LAST_MODIFIED);
				if (aHeaders.length > 0) {
					strLastModify = aHeaders[0].getValue();
				}
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

		finally {
			httpclient.getConnectionManager().shutdown();
		}

		return strLastModify;
	}
    
	public static boolean isModify(String url, String strLastModifyTime) {
		boolean bOk = false;
		HttpClient httpclient = new DefaultHttpClient();
		try {
			httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
			httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 60000);
			HttpHead httphead = new HttpHead(url);
			httphead.addHeader(HttpHeaders.IF_MODIFIED_SINCE, strLastModifyTime);
			HttpResponse response = httpclient.execute(httphead);
			int nCode = response.getStatusLine().getStatusCode();
			if (nCode == 304) {
				bOk = true;
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

		finally {
			httpclient.getConnectionManager().shutdown();
		}

		return bOk;

	}
}
